package com.gy.assistant.ui.conversationlist;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.function.Predicate;
import java.util.stream.Collectors;


import im.zego.zim.entity.ZIMCombineMessage;
import im.zego.zim.entity.ZIMConversation;
import im.zego.zim.entity.ZIMCustomMessage;
import im.zego.zim.entity.ZIMMessageReaction;
import im.zego.zim.entity.ZIMMessageReactionUserInfo;
import im.zego.zim.entity.ZIMSystemMessage;
import im.zego.zim.entity.ZIMTextMessage;
import im.zego.zim.enums.ZIMConversationNotificationStatus;
import im.zego.zim.enums.ZIMConversationType;
import im.zego.zim.enums.ZIMMessageType;
import com.gy.assistant.R;
import com.gy.assistant.util.GlideUtils;
import com.gy.assistant.util.TimeTools;

public class ConversationListAdapter extends RecyclerView.Adapter {

    private OnItemClickListener onItemClickListener;
    private OnItemLongClickListener onItemLongClickListener;
    private List<ZIMConversation> conversationList = new ArrayList<>();

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_conversation, parent, false);
        return new ConversationViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        final ConversationViewHolder conversationViewHolder = (ConversationViewHolder) holder;

        ZIMConversation conversation = conversationList.get(position);
        conversationViewHolder.setConversationInfo(conversation);

        if (onItemClickListener != null) {
            conversationViewHolder.list.setOnClickListener(v -> {
                onItemClickListener.onItemClick(v, conversation);
            });
        }

        if (onItemLongClickListener != null) {
            conversationViewHolder.list.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    onItemLongClickListener.onItemRemove(v, conversation);
                    return true;
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return conversationList.size();
    }

    public void addOrUpdate(ZIMConversation newO) {
        // 为了兼容会话可能不同类型的会话会有相同convId的问题
        ZIMConversation oldConversation = null;
        for (ZIMConversation zimConversation : conversationList) {
            if (zimConversation.conversationID.equals(newO.conversationID)  && zimConversation.type == newO.type){
                oldConversation = zimConversation;
                break;
            }
        }
        if (oldConversation !=null){
            conversationList.remove(oldConversation);
        }
        conversationList.add(newO);
    }

    public void updateNotificationStatus(String conversationID, ZIMConversationType conversationType,ZIMConversationNotificationStatus status){
        ZIMConversation oldConversation = null;
        for (ZIMConversation zimConversation : conversationList) {
            if (zimConversation.conversationID.equals(conversationID)  && zimConversation.type == conversationType){
                oldConversation = zimConversation;
                break;
            }
        }
        if (oldConversation!=null){
            oldConversation.notificationStatus = status;
            int index = conversationList.indexOf(oldConversation);
            notifyItemChanged(index);
        }
    }

    public void delete(ZIMConversation delO) {
        // 为了兼容会话可能不同类型的会话会有相同convId的问题
        conversationList.removeIf(new Predicate<ZIMConversation>() {
            @Override
            public boolean test(ZIMConversation zimConversation) {
                return zimConversation.conversationID.equals(delO.conversationID ) && zimConversation.type == delO.type;
            }
        });
    }

    @Nullable
    public ZIMConversation getLastConversation() {
        if (conversationList.size() > 0) {
            return conversationList.get(conversationList.size() - 1);
        }
        return null;
    }

    public void sortAndNotify() {
        conversationList = conversationList.stream().sorted(new Comparator<ZIMConversation>() {
            @Override
            public int compare(ZIMConversation o1, ZIMConversation o2) {
                if (o1.orderKey < o2.orderKey) {
                    return 1;
                }
                return -1;
            }
        }).collect(Collectors.toList());
        notifyItemRangeChanged(0,conversationList.size());
    }

    public void setOnItemClickListener(OnItemClickListener mOnItemClickListener) {
        this.onItemClickListener = mOnItemClickListener;
    }

    public interface OnItemClickListener {
        void onItemClick(View view, ZIMConversation conversation);
    }

    public void setOnItemLongClickListener(OnItemLongClickListener onItemLongClickListener) {
        this.onItemLongClickListener = onItemLongClickListener;
    }

    public interface OnItemLongClickListener {
        void onItemRemove(View view, ZIMConversation conversation);
    }


    public static class ConversationViewHolder extends RecyclerView.ViewHolder {
        TextView userNameTextView;
        ImageView avatarImageView;
        TextView contentTextView;
        TextView timeTextView;
        TextView countTextView;
        TextView mentionCountTextView;
        RelativeLayout list;

        TextView tvReaction;
        ImageView ivNotification;
        public ConversationViewHolder(View itemView) {
            super(itemView);
            list = itemView.findViewById(R.id.list);
            userNameTextView = itemView.findViewById(R.id.user_name);
            avatarImageView = itemView.findViewById(R.id.avatar);
            contentTextView = itemView.findViewById(R.id.content);
            timeTextView = itemView.findViewById(R.id.time);
            countTextView = itemView.findViewById(R.id.count);
            mentionCountTextView = itemView.findViewById(R.id.tv_mention_count);
            tvReaction = itemView.findViewById(R.id.tv_reactions);
            ivNotification = itemView.findViewById(R.id.iv_notification);
        }

        public void setConversationInfo(ZIMConversation conversation) {
            String conversationName = conversation.conversationID;
            if (conversation.isPinned){
                list.setBackgroundColor(ContextCompat.getColor(list.getContext(), R.color.lfile_lightgray));
            }else {
                list.setBackgroundColor(ContextCompat.getColor(list.getContext(), R.color.white));
            }
            if (conversation.conversationName != null && !"".equals(conversation.conversationName)) {
                conversationName = conversation.conversationName;
            }
            if (conversation.type == ZIMConversationType.PEER) {
                userNameTextView.setText(userNameTextView.getContext().getString(R.string.tab_peer) + conversationName);
            } else if (conversation.type == ZIMConversationType.GROUP) {
                userNameTextView.setText(userNameTextView.getContext().getString(R.string.tab_group) + conversationName);
            } else if (conversation.type == ZIMConversationType.ROOM) {
                userNameTextView.setText(userNameTextView.getContext().getString(R.string.tab_room) + conversationName);
            }
            if (conversation.notificationStatus == ZIMConversationNotificationStatus.DO_NOT_DISTURB){
                ivNotification.setVisibility(View.VISIBLE);
            }else {
                ivNotification.setVisibility(View.GONE);
            }
            if (!conversation.draft.isEmpty()){
                contentTextView.setText(String.format("[草稿]:%s",conversation.draft));
            }else {
                if (conversation.lastMessage != null) {
                    StringBuilder reactions = new StringBuilder();
                    for (ZIMMessageReaction reaction : conversation.lastMessage.getReactions()) {
                        StringBuilder reactionStr = new StringBuilder(reaction.reactionType);
                        reactionStr.append("(");
                        reactionStr.append(reaction.totalCount);
                        reactionStr.append("):");
                        for (ZIMMessageReactionUserInfo userInfo : reaction.userList) {
                            reactionStr.append(userInfo.userID);
                            reactionStr.append(",");
                        }
                        reactions.append(reactionStr);
                    }
                    tvReaction.setText(reactions.toString());
                    if (conversation.lastMessage.getType() == ZIMMessageType.CUSTOM) {
                        ZIMCustomMessage customMessage = (ZIMCustomMessage) conversation.lastMessage;
                        contentTextView.setText(String.format(Locale.getDefault(),"[custom],[%d],[%s]%s",customMessage.subType,customMessage.searchedContent,customMessage.message));
                    }else if (conversation.lastMessage.getType() == ZIMMessageType.TEXT) {
                        ZIMTextMessage zimTextMessage = (ZIMTextMessage) conversation.lastMessage;
                        contentTextView.setText(zimTextMessage.message);
                    } else if (conversation.lastMessage.getType() == ZIMMessageType.COMMAND) {
                        contentTextView.setText(countTextView.getContext().getString(R.string.tx_signaling_message));
                    } else if (conversation.lastMessage.getType() == ZIMMessageType.IMAGE) {
                        contentTextView.setText(countTextView.getContext().getString(R.string.tx_image_message));
                    } else if (conversation.lastMessage.getType() == ZIMMessageType.FILE) {
                        contentTextView.setText(countTextView.getContext().getString(R.string.tx_file_message));
                    } else if (conversation.lastMessage.getType() == ZIMMessageType.AUDIO) {
                        contentTextView.setText(countTextView.getContext().getString(R.string.tx_audio_message));
                    } else if (conversation.lastMessage.getType() == ZIMMessageType.VIDEO) {
                        contentTextView.setText(countTextView.getContext().getString(R.string.tx_video_message));
                    }else if (conversation.lastMessage.getType() == ZIMMessageType.SYSTEM){
                        ZIMSystemMessage zimTextMessage = (ZIMSystemMessage) conversation.lastMessage;
                        contentTextView.setText("system :"+zimTextMessage.message);
                    }else if (conversation.lastMessage.getType() == ZIMMessageType.REVOKE){
                        contentTextView.setText("该消息已被撤回");
                    }else if (conversation.lastMessage.getType() == ZIMMessageType.COMBINE){
                        ZIMCombineMessage zimCombineMessage = (ZIMCombineMessage) conversation.lastMessage;
                        contentTextView.setText(String.format("title:%s,summary:%s",zimCombineMessage.title,zimCombineMessage.summary));
                    }

                    timeTextView.setText(TimeTools.longFormatTime(conversation.lastMessage.getTimestamp(), this.contentTextView.getContext()));
                } else {
                    contentTextView.setText("");
                    timeTextView.setText("");
                }
            }
            GlideUtils.loadUrl(avatarImageView, conversation.conversationAvatarUrl);
            if (conversation.unreadMessageCount > 0) {
                countTextView.setVisibility(View.VISIBLE);
                countTextView.setText(String.valueOf(conversation.unreadMessageCount));
            } else {
                countTextView.setVisibility(View.GONE);
            }

            if (!conversation.mentionedInfoList.isEmpty()){
                mentionCountTextView.setVisibility(View.VISIBLE);
                mentionCountTextView.setText(conversation.mentionedInfoList.size() +" @");
            }else {
                mentionCountTextView.setVisibility(View.GONE);
            }

        }
    }
}
